package com.yenlien.traceyun.breed.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.breed.entity.Born;
import com.yenlien.traceyun.breed.service.BornService;
import com.yenlien.traceyun.business.interceptor.DataAuth;
import com.yenlien.traceyun.webase.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
 * 繁殖管理控制层
 *
 * @author maybe
 * @date 2020年10月12日
 */
@RestController
@RequestMapping("/born")
public class BornController extends BaseController {
    @Autowired
    private BornService bornService;

    //分页查询列表
    @DataAuth
    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody JSONObject params) {
        Born born = new Born();
        born.setBreedName(params.getString("searchName"));
        born.setBatch(params.getString("batch"));
        born.setPage(params.getIntValue("page"));
        born.setPageSize(params.getIntValue("pageSize"));
        return buildPage(bornService.findByList(born));
    }

    //新增繁殖
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(@RequestBody Born born) {
        bornService.save(born);
        return success("success");
    }

    //根据母源类型和编码查询详情
    @RequestMapping(value = "/findByTypeAndCode", method = RequestMethod.POST)
    public Object findByTypeAndCode(@RequestBody JSONObject params) {
        return success(bornService.findByTypeAndCode(params));
    }

    //根据ID查询繁殖详情
    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable("id") String id) {
        return success(bornService.findById(id));
    }

    //导入母源码
    @RequestMapping(value = "/inCode")
    @ResponseBody
    public Object inCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartFile multipartFile = ((MultipartHttpServletRequest) request).getFile("file");
        Reader reader = null;
        List<String> list = new ArrayList<>();
        reader = new InputStreamReader(multipartFile.getInputStream(), "utf-8");
        BufferedReader br = new BufferedReader(reader);
        String line;
        while ((line = br.readLine()) != null) {
            // 一次读入一行数据
            list.add(line);
        }
        reader.close();
        return success(bornService.findByTypeAndCodeList(request.getParameter("type"), list));
    }
}
